package com.fridge.setting;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;
import com.id2216.fridge.R;

public class LoginFragment extends Fragment {
	
	private EditText postText;
	private ImageButton selectPostImage;
	private ImageView postImageView;
	private Button shareButton;
	
	private String postMessage;
	private Uri postImageUri;
	private static final int SELECT_IMAGE = 100;
	
	private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;
	
	
	
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(Session session, SessionState state, Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	
		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	    View view = inflater.inflate(R.layout.login, container, false);
	    
	    LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
	    authButton.setFragment(this);
	    
	    postText = (EditText) view.findViewById(R.id.postMessageText);
	    postImageView = (ImageView) view.findViewById(R.id.postImageView);
	    
	    selectPostImage = (ImageButton) view.findViewById(R.id.selectPostImageButton);
		selectPostImage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Intent selectImageIntent = new Intent(Intent.ACTION_PICK);
				selectImageIntent.setType("image/*");
				startActivityForResult(selectImageIntent, SELECT_IMAGE);				
			}
		});
	    
	    shareButton = (Button) view.findViewById(R.id.shareButton);
	    shareButton.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	            publishStory();
	        }
	    });
	    
	    if (savedInstanceState != null) {
	        pendingPublishReauthorization = 
	            savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
	    }

	    return view;
	}
	
	
	
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		
	    if (state.isOpened()) {
	    	
	    	postText.setVisibility(View.VISIBLE);
	    	selectPostImage.setVisibility(View.VISIBLE);
	    	postImageView.setVisibility(View.VISIBLE);
	    	shareButton.setVisibility(View.VISIBLE);
	    	
	    	if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
	    	    pendingPublishReauthorization = false;
	    	    publishStory();//function for dialog
	    	}
	    }
	    else if (state.isClosed()) {
	    	
	    	postText.setVisibility(View.INVISIBLE);
	    	selectPostImage.setVisibility(View.INVISIBLE);
	    	postImageView.setVisibility(View.INVISIBLE);
	    	shareButton.setVisibility(View.INVISIBLE);
	    }
	}
	
	
	
	private UiLifecycleHelper uiHelper;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    uiHelper = new UiLifecycleHelper(this.getActivity(), callback);
	    uiHelper.onCreate(savedInstanceState);
	    
	}
	
	
	
	@Override
	public void onResume() {
	    super.onResume();
	    
	    // For scenarios where the main activity is launched and user
	    // session is not null, the session state change notification
	    // may not be triggered. Trigger it if it's open/closed.
	    Session session = Session.getActiveSession();
	    if (session != null &&
	           (session.isOpened() || session.isClosed()) ) {
	        onSessionStateChange(session, session.getState(), null);
	    }
	    
	    uiHelper.onResume();
	}
	
	

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    
		switch (requestCode) {
		case SELECT_IMAGE:
			if (resultCode == -1) {
				postImageUri  = data.getData();
				postImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				postImageView.setPadding(8, 8, 8, 8);
				postImageView.setImageURI(postImageUri);
			}
			break;
		}
	    
		uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
			@Override
			public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
				Log.e("Activity", String.format("Error: %s", error.toString()));
			}

			@Override
			public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
				Log.i("Activity", "Success!");
			}
		});
	}
	
	

	@Override
	public void onPause() {
	    super.onPause();
	    uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
	    super.onDestroy();
	    uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
	    uiHelper.onSaveInstanceState(outState);
	}
	
 
	private void publishStory() {
		Session session = Session.getActiveSession();

		if (session != null) {

			// Check for publish permissions
			List<String> permissions = session.getPermissions();
			if (!isSubsetOf(PERMISSIONS, permissions)) {
				pendingPublishReauthorization = true;
				Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
						this, PERMISSIONS);
				session.requestNewPublishPermissions(newPermissionsRequest);
				return;
			}
		}
		
		Bitmap image = null;
		if (postImageUri != null) {
			
			try {
				image = MediaStore.Images.Media.getBitmap(this.getActivity().getContentResolver(), postImageUri);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
        Request imageRequest = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
            @Override
            public void onCompleted(Response response) {
            	FacebookRequestError error = response.getError();
            	if (error != null) {
            		Toast.makeText(getActivity(), error.getErrorMessage(), Toast.LENGTH_SHORT).show();
            	}
            	else {
            		Toast.makeText(getActivity(), "Posted successful on your wall", Toast.LENGTH_SHORT).show();
            	}
            	
            }
        });
        
        if (postText.getText() != null) {
        	postMessage = postText.getText().toString();
        } 
		
		Bundle params = imageRequest.getParameters();
		params.putString("message", postMessage);
		imageRequest.executeAsync();
		
        postText.setText(null);
        postImageView.setImageURI(null);
		
	}
	
	private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
	    for (String string : subset) {
	        if (!superset.contains(string)) {
	            return false;
	        }
	    }
	    return true;
	}
	
}
